﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Rad_Studio_Keygen
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }

        bool threadRunning = true;
        private void Form1_Load(object sender, EventArgs e)
        {
            cbb_Version.Items.Clear();
            foreach (var rv in RadStudioVersion.RadStudioVersionList)
            {
                cbb_Version.Items.Add(rv.Name);
            }
            cbb_Version.SelectedIndex = 0;

            tb_SN.Text = RadKeygen.GenerateSerialNumber();
            tb_RegCode.Text = RadKeygen.GetRegistrationCode();
            CheckForIllegalCrossThreadCalls = false;

            waitingPatchThread = new Thread(() => WaitingPatchThread());

        }

        RadStudioVersion GetCurrentVersion()
        {
            return RadStudioVersion.RadStudioVersionList.Select(rsv => rsv).Where(rsv => rsv.Name == cbb_Version.Text).FirstOrDefault();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (tb_RegCode.Text == "")
                tb_RegCode.Text = RadKeygen.GetRegistrationCode();
            if (tb_RegCode.Text.Trim() != "")
            {
                string FileName = "";
                if (RadKeygen.GenerateLicenseFile(tb_SN.Text, tb_RegCode.Text, GetCurrentVersion(), ref FileName))
                {
                    MessageBox.Show($"Slip文件保存成功！\n{FileName}", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show($"保存Slip文件时发生错误！", "失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show($"请启动安装程序并到请求授权界面", "失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        void WaitingPatchThread()
        {
            var cv = GetCurrentVersion();
            var RootDir = RadKeygen.GetRootDir(cv);
            while (RootDir == null)
            {
                RootDir = RadKeygen.GetRootDir(cv);
                Thread.Sleep(100);
                if (!threadRunning)
                    return;
            }
            var FileName = "";
            RadKeygen.PatchFile(cv, ref FileName);
        }

        Thread waitingPatchThread;
        private void button4_Click(object sender, EventArgs e)
        {
            threadRunning = true;
            button1_Click(null, null);
            if (tb_RegCode.Text.Trim() != "")
            {
                var cv = GetCurrentVersion();
                RadKeygen.PatchmOasisRuntime(cv);
                var version = float.Parse(cv.BDSVersion);
                if (version >= 21.0)
                {
                    if (this.waitingPatchThread.ThreadState == System.Threading.ThreadState.Stopped)
                    {
                        waitingPatchThread = new Thread(() => WaitingPatchThread());
                    }
                    if (this.waitingPatchThread.ThreadState != System.Threading.ThreadState.Running)
                        this.waitingPatchThread.Start();
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string FileName = "";
            if (RadKeygen.PatchFile(GetCurrentVersion(), ref FileName))
            {
                MessageBox.Show($"补丁文件保存成功！\n{FileName}", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show($"补丁文件失败！", "失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            tb_SN.Text = RadKeygen.GenerateSerialNumber();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var cv = GetCurrentVersion();

            var cvt = new MarkupConverter.MarkupConverter();
            var tmp = Properties.Resources.Info;
            tmp = tmp.Replace("<Name>", cv.Name);
            tmp = tmp.Replace("<Ver>", cv.Ver);
            tmp = tmp.Replace("<ISOUrl>", cv.ISOUrl);
            tmp = tmp.Replace("<ISOMd5>", cv.ISOMd5);
            richTextBox1.Rtf = tmp;

            this.Text = $"Rad Studio Keygen {cv.Name}";
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            threadRunning = false;
        }
        private void FormMain_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                var file = ((string[])e.Data.GetData(DataFormats.FileDrop))[0];
                PPPP(file);
            }
        }

        private void FormMain_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        public static void PPPP(string file)
        {
            var ext = Path.GetExtension(file);
            var s = "";
            if (".cg_license" == ext || ext == ".cgb_license")
            {
                var key = 0xED864640;
                while (true)
                {
                    try
                    {

                        var bytes = RadKeygen.DeCryptoFile(file, key);// RadKeygen.GetKey());
                        if (bytes != null)
                        {
                            s = Encoding.ASCII.GetString(bytes);
                            var rl = new CGLicense(s);
                            break;
                        }
                    }catch (Exception ex) { }
                    key += 0x10;
                }
            }
            else if (ext == ".slip")
            {
                var bytes = RadKeygen.DeCryptoFile(file, 0xE7F931C2);
                if (bytes != null)
                {
                    s = Encoding.UTF8.GetString(bytes);
                    var rl = new RadLicense(s);
                }
            }
        }

        private void FormMain_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            PPPP(@"C:\ProgramData\Embarcadero\.8222_52.1934065768721.slip");
        }
    }
}
